package top.kaoshanji.r3ch11a;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码清单-r3ch11a-364页a：ThreadLocal简单版本
 * @author kaoshanji
 * ^_^
 * create time 2025/5/8 18:31
 */
public class SimpleThreadLocal {

    private Map valueMap = Collections.synchronizedMap(new HashMap<>());

    public void set(Object newValue) {
        // 键为线程对象，值为本线程的变量副本
        valueMap.put(Thread.currentThread(), newValue);
    }

    public Object get() {
        Thread currentThread = Thread.currentThread();
        Object o = valueMap.get(currentThread); // 返回本线程对应的变量

        // 如果在 Map 中不存在，则放到 Map 中保存起来
        if (o == null && !valueMap.containsKey(currentThread)) {
            o = initialValue();
            valueMap.put(currentThread, o);
        }

        return o;
    }

    public void remove() {
        valueMap.remove(Thread.currentThread());
    }

    public Object initialValue() {
        return null;
    }





}
